Popular Searches
Popular Course Categories
Popular Courses

Page Object Model

Test Automation Framework

Page Object Model (POM) in Selenium

Page Object Model (POM) is a design pattern used in Selenium automation testing to create maintainable, reusable, readable, and scalable automation scripts. In POM, every important page or reusable component of a web application is represented by a separate Java class. The class contains the locators and methods required to interact with that page or component.

The main purpose of POM is to separate test logic from page interaction logic. Instead of writing Selenium locators and WebDriver commands directly inside every test case, they are organized inside page classes. This reduces code duplication and makes automation scripts easier to maintain when the application's UI changes.

JustAcademy's Selenium Training covers Page Object Model (POM) as part of Selenium automation framework development, along with TestNG, Data-Driven Testing, Keyword-Driven Framework, Hybrid Framework Design, reusable test architecture, reporting, logging, debugging, Selenium Grid, and CI/CD concepts.

Selenium Training | Register for Course Demo


1. What Is Page Object Model?

Page Object Model is a Selenium design pattern in which web pages are represented as Java classes. Each page class generally contains the locators of elements available on that page and methods that describe the actions that can be performed on those elements.

For example, if an application contains Login, Home, Product, Cart, and Checkout pages, we can create separate classes:

LoginPage.java

HomePage.java

ProductPage.java

CartPage.java

CheckoutPage.java

Each class represents the behavior and elements of its corresponding page.


2. Simple Definition

Page Object Model = Represent each application page as a reusable object containing its locators and page-specific actions.

Instead of writing:

driver.findElement(By.id("username"))

      .sendKeys("testuser");

 

driver.findElement(By.id("password"))

      .sendKeys("password");

 

driver.findElement(By.id("login"))

      .click();

inside every test, we can create a LoginPage class:

LoginPage loginPage = new LoginPage(driver);

 

loginPage.enterUsername("testuser");

loginPage.enterPassword("password");

loginPage.clickLogin();


3. Why Do We Need POM?

Without POM, Selenium tests can become difficult to maintain because locators and WebDriver commands are repeated throughout multiple test classes.

Test Case 1

    ↓

Login Locators

 

Test Case 2

    ↓

Login Locators

 

Test Case 3

    ↓

Login Locators

 

Test Case 4

    ↓

Login Locators

If the login button's locator changes, multiple test cases may need to be updated.

With POM:

LoginPage

    ↓

Login Locators

    ↓

Test Case 1

Test Case 2

Test Case 3

Test Case 4

The locator can be maintained in one central location.


4. Main Objectives of POM

  • Separate test logic from page interaction logic.
  • Reduce duplicate Selenium code.
  • Centralize locators.
  • Improve test readability.
  • Improve maintainability.
  • Increase code reusability.
  • Make UI changes easier to manage.
  • Support scalable automation frameworks.
  • Improve collaboration among automation testers.
  • Make test cases easier to understand.


5. Basic POM Architecture

                Test Class

                    |

                    ↓

               Page Object

                    |

        +-----------+-----------+

        |                       |

     Locators                Methods

        |                       |

        +-----------+-----------+

                    |

                    ↓

             Selenium WebDriver

                    |

                    ↓

                  Browser

                    |

                    ↓

             Web Application


6. POM Components

ComponentPurpose
Page ClassRepresents a web page or application component
LocatorsIdentify web elements
Page MethodsPerform actions on the page
WebDriverControls the browser
Test ClassContains test scenarios and validations
AssertionsValidate expected results


7. Example Application

Consider an e-commerce application with the following pages:

Login Page

    ↓

Home Page

    ↓

Search Page

    ↓

Product Page

    ↓

Cart Page

    ↓

Checkout Page

Using POM, we can create:

LoginPage.java

HomePage.java

SearchPage.java

ProductPage.java

CartPage.java

CheckoutPage.java


8. Creating a LoginPage Class

package pages;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class LoginPage {

 

    private WebDriver driver;

 

    private By username =

        By.id("username");

 

    private By password =

        By.id("password");

 

    private By loginButton =

        By.id("login");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterUsername(String value) {

        driver.findElement(username)

              .sendKeys(value);

    }

 

    public void enterPassword(String value) {

        driver.findElement(password)

              .sendKeys(value);

    }

 

    public void clickLogin() {

        driver.findElement(loginButton)

              .click();

    }

 

    public void login(String usernameValue,

                      String passwordValue) {

        enterUsername(usernameValue);

        enterPassword(passwordValue);

        clickLogin();

    }

}


9. Understanding the LoginPage Class

The class contains four important parts:

  1. WebDriver object.
  2. Locators.
  3. Constructor.
  4. Page interaction methods.


10. WebDriver Variable

private WebDriver driver;

This variable stores the WebDriver instance used by the page object to interact with the browser.


11. Locators in POM

Locators identify elements on a web page.

private By username =

    By.id("username");

 

private By password =

    By.id("password");

 

private By loginButton =

    By.id("login");

Common Selenium locators include:

  • id
  • name
  • className
  • tagName
  • linkText
  • partialLinkText
  • cssSelector
  • XPath


12. Why Keep Locators Private?

Locators are generally declared as private because the test should interact with the page through meaningful methods instead of directly manipulating internal locator definitions.

private By username = By.id("username");

The test uses:

loginPage.enterUsername("testuser");

instead of:

driver.findElement(

    By.id("username")

).sendKeys("testuser");


13. Constructor in POM

The constructor receives the WebDriver object from the test or base class.

public LoginPage(WebDriver driver) {

    this.driver = driver;

}

This allows the page class to use the same browser session created by the test framework.


14. Page Methods

Page methods represent actions that a user can perform on a page.

public void enterUsername(String value) {

    driver.findElement(username)

          .sendKeys(value);

}

 

public void enterPassword(String value) {

    driver.findElement(password)

          .sendKeys(value);

}

 

public void clickLogin() {

    driver.findElement(loginButton)

          .click();

}


15. Test Class Using POM

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.Test;

 

public class LoginTest {

 

    @Test

    public void validLoginTest() {

 

        WebDriver driver =

            new ChromeDriver();

 

        driver.get(

            "https://example.com/login"

        );

 

        LoginPage loginPage =

            new LoginPage(driver);

 

        loginPage.enterUsername(

            "testuser"

        );

 

        loginPage.enterPassword(

            "password"

        );

 

        loginPage.clickLogin();

 

        driver.quit();

    }

}


16. POM Test Execution Flow

TestNG Test

     ↓

Create WebDriver

     ↓

Open Application

     ↓

Create LoginPage Object

     ↓

Call Page Method

     ↓

Page Method Uses Locator

     ↓

Selenium WebDriver

     ↓

Browser

     ↓

Application


17. POM With Login Method

Instead of calling three separate methods from the test, we can create a reusable business action called login().

public void login(

        String usernameValue,

        String passwordValue) {

 

    enterUsername(usernameValue);

    enterPassword(passwordValue);

    clickLogin();

}

The test becomes:

LoginPage loginPage =

    new LoginPage(driver);

 

loginPage.login(

    "testuser",

    "password"

);


18. Why Business Methods Are Useful

Business-level methods make test cases easier to read.

Instead of:

enterUsername();

enterPassword();

clickLogin();

the test can simply say:

loginPage.login(

    username,

    password

);

This describes the business action rather than exposing every low-level Selenium operation.


19. Creating a HomePage Class

package pages;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class HomePage {

 

    private WebDriver driver;

 

    private By searchBox =

        By.id("search");

 

    private By logoutButton =

        By.id("logout");

 

    public HomePage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void searchProduct(String product) {

        driver.findElement(searchBox)

              .sendKeys(product);

    }

 

    public void logout() {

        driver.findElement(logoutButton)

              .click();

    }

}


20. Creating a ProductPage Class

package pages;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class ProductPage {

 

    private WebDriver driver;

 

    private By addToCart =

        By.id("addToCart");

 

    public ProductPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void addProductToCart() {

        driver.findElement(addToCart)

              .click();

    }

}


21. Creating a CartPage Class

package pages;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class CartPage {

 

    private WebDriver driver;

 

    private By checkoutButton =

        By.id("checkout");

 

    private By cartTotal =

        By.id("cartTotal");

 

    public CartPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void clickCheckout() {

        driver.findElement(checkoutButton)

              .click();

    }

 

    public String getCartTotal() {

        return driver.findElement(cartTotal)

                     .getText();

    }

}


22. Creating a CheckoutPage Class

package pages;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

 

public class CheckoutPage {

 

    private WebDriver driver;

 

    private By firstName =

        By.id("firstName");

 

    private By address =

        By.id("address");

 

    private By placeOrder =

        By.id("placeOrder");

 

    public CheckoutPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterFirstName(String value) {

        driver.findElement(firstName)

              .sendKeys(value);

    }

 

    public void enterAddress(String value) {

        driver.findElement(address)

              .sendKeys(value);

    }

 

    public void placeOrder() {

        driver.findElement(placeOrder)

              .click();

    }

}


23. Complete E-Commerce Flow Using POM

LoginPage

    ↓

login()

    ↓

HomePage

    ↓

searchProduct()

    ↓

ProductPage

    ↓

addProductToCart()

    ↓

CartPage

    ↓

clickCheckout()

    ↓

CheckoutPage

    ↓

placeOrder()


24. Complete Test Example

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.Test;

 

public class ECommerceTest {

 

    @Test

    public void purchaseProduct() {

 

        WebDriver driver =

            new ChromeDriver();

 

        driver.manage()

              .window()

              .maximize();

 

        driver.get(

            "https://example.com"

        );

 

        LoginPage loginPage =

            new LoginPage(driver);

 

        HomePage homePage =

            new HomePage(driver);

 

        ProductPage productPage =

            new ProductPage(driver);

 

        CartPage cartPage =

            new CartPage(driver);

 

        CheckoutPage checkoutPage =

            new CheckoutPage(driver);

 

        loginPage.login(

            "testuser",

            "password"

        );

 

        homePage.searchProduct(

            "Laptop"

        );

 

        productPage.addProductToCart();

 

        cartPage.clickCheckout();

 

        checkoutPage.enterFirstName(

            "Test User"

        );

 

        checkoutPage.enterAddress(

            "Mumbai"

        );

 

        checkoutPage.placeOrder();

 

        driver.quit();

    }

}


25. POM With TestNG

POM is commonly used together with TestNG in Selenium automation frameworks.

public class LoginTest extends BaseTest {

 

    @Test

    public void validLogin() {

 

        LoginPage loginPage =

            new LoginPage(driver);

 

        loginPage.login(

            "testuser",

            "password"

        );

    }

}


26. Base Test With POM

A BaseTest class can handle common browser setup and teardown.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.*;

 

public class BaseTest {

 

    protected WebDriver driver;

 

    @BeforeMethod

    public void setUp() {

 

        driver = new ChromeDriver();

 

        driver.manage()

              .window()

              .maximize();

 

        driver.get(

            "https://example.com"

        );

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


27. Login Test Extending BaseTest

public class LoginTest extends BaseTest {

 

    @Test

    public void validLoginTest() {

 

        LoginPage loginPage =

            new LoginPage(driver);

 

        loginPage.login(

            "testuser",

            "password"

        );

    }

}


28. POM With Assertions

Assertions should generally remain in the test or validation layer rather than being unnecessarily mixed into low-level page interaction methods.

import org.testng.Assert;

import org.testng.annotations.Test;

 

public class LoginTest extends BaseTest {

 

    @Test

    public void verifyLogin() {

 

        LoginPage loginPage =

            new LoginPage(driver);

 

        loginPage.login(

            "testuser",

            "password"

        );

 

        Assert.assertEquals(

            driver.getTitle(),

            "Home Page"

        );

    }

}


29. POM With Page Verification Methods

Page classes can expose meaningful state-check methods when they are useful for test readability.

public boolean isLogoutButtonDisplayed() {

 

    return driver.findElement(

        logoutButton

    ).isDisplayed();

}

The test can then use:

Assert.assertTrue(

    homePage.isLogoutButtonDisplayed()

);


30. POM With Explicit Wait

For modern dynamic applications, page objects often use explicit waits before interacting with elements.

import java.time.Duration;

import org.openqa.selenium.*;

import org.openqa.selenium.support.ui.*;

 

public class LoginPage {

 

    private WebDriver driver;

    private WebDriverWait wait;

 

    private By username =

        By.id("username");

 

    private By password =

        By.id("password");

 

    private By loginButton =

        By.id("login");

 

    public LoginPage(WebDriver driver) {

 

        this.driver = driver;

 

        wait = new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

    }

 

    public void enterUsername(String value) {

 

        wait.until(

            ExpectedConditions

                .visibilityOfElementLocated(

                    username

                )

        ).sendKeys(value);

    }

 

    public void enterPassword(String value) {

 

        wait.until(

            ExpectedConditions

                .visibilityOfElementLocated(

                    password

                )

        ).sendKeys(value);

    }

 

    public void clickLogin() {

 

        wait.until(

            ExpectedConditions

                .elementToBeClickable(

                    loginButton

                )

        ).click();

    }

}


31. POM With PageFactory

Selenium projects may also use the PageFactory style of declaring page elements.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.*;

 

public class LoginPage {

 

    private WebDriver driver;

 

    @FindBy(id = "username")

    private WebElement username;

 

    @FindBy(id = "password")

    private WebElement password;

 

    @FindBy(id = "login")

    private WebElement loginButton;

 

    public LoginPage(WebDriver driver) {

 

        this.driver = driver;

 

        PageFactory.initElements(

            driver,

            this

        );

    }

 

    public void login(

            String user,

            String pass) {

 

        username.sendKeys(user);

        password.sendKeys(pass);

        loginButton.click();

    }

}


32. By Locator vs WebElement

ApproachExampleCommon Use
By LocatorBy.id("username")Explicit locator-based interaction
WebElementWebElement usernamePageFactory-style page objects

Both approaches can be used to implement page objects. The choice should be consistent with the project's framework standards.


33. POM With XPath

private By username =

    By.xpath("//input[@name='username']");

 

private By loginButton =

    By.xpath("//button[@type='submit']");

Prefer stable and meaningful locators whenever possible.


34. POM With CSS Selector

private By username =

    By.cssSelector("#username");

 

private By loginButton =

    By.cssSelector("button[type='submit']");


35. POM With Dropdowns

import org.openqa.selenium.support.ui.Select;

 

private By countryDropdown =

    By.id("country");

 

public void selectCountry(String country) {

 

    Select select =

        new Select(

            driver.findElement(

                countryDropdown

            )

        );

 

    select.selectByVisibleText(country);

}


36. POM With Checkboxes

private By termsCheckbox =

    By.id("terms");

 

public void selectTerms() {

 

    WebElement checkbox =

        driver.findElement(

            termsCheckbox

        );

 

    if (!checkbox.isSelected()) {

        checkbox.click();

    }

}


37. POM With Radio Buttons

private By maleRadio =

    By.id("male");

 

public void selectMale() {

 

    WebElement radio =

        driver.findElement(maleRadio);

 

    if (!radio.isSelected()) {

        radio.click();

    }

}


38. POM With Alerts

public void acceptAlert() {

 

    driver.switchTo()

          .alert()

          .accept();

}


39. POM With Frames

public void switchToPaymentFrame() {

 

    driver.switchTo()

          .frame("paymentFrame");

}

 

public void switchToMainPage() {

 

    driver.switchTo()

          .defaultContent();

}


40. POM With Multiple Windows

public void switchToNewWindow() {

 

    String parent =

        driver.getWindowHandle();

 

    for (String window :

         driver.getWindowHandles()) {

 

        if (!window.equals(parent)) {

 

            driver.switchTo()

                  .window(window);

        }

    }

}


41. POM With Mouse Actions

import org.openqa.selenium.interactions.Actions;

 

public void hoverOverMenu(By locator) {

 

    WebElement element =

        driver.findElement(locator);

 

    Actions actions =

        new Actions(driver);

 

    actions.moveToElement(element)

           .perform();

}


42. POM With JavaScript

import org.openqa.selenium.JavascriptExecutor;

 

public void scrollToElement(

        WebElement element) {

 

    JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

    js.executeScript(

        "arguments[0].scrollIntoView(true);",

        element

    );

}


43. POM With Data-Driven Testing

POM can be combined with Data-Driven Testing. The page class handles UI interaction while external data provides different input values.

@DataProvider(name = "loginData")

public Object[][] loginData() {

 

    return new Object[][] {

        {"user1", "pass1"},

        {"user2", "pass2"},

        {"user3", "pass3"}

    };

}

 

@Test(dataProvider = "loginData")

public void loginTest(

        String username,

        String password) {

 

    LoginPage loginPage =

        new LoginPage(driver);

 

    loginPage.login(

        username,

        password

    );

}


44. POM With Excel

Excel can store multiple sets of test data while POM handles the page interactions.

Excel

  ↓

Excel Utility

  ↓

TestNG DataProvider

  ↓

Test Class

  ↓

LoginPage

  ↓

Selenium WebDriver

  ↓

Browser


45. POM With Keyword-Driven Framework

POM can also be combined with a Keyword-Driven Framework.

Keyword

   ↓

Keyword Library

   ↓

Page Object

   ↓

Selenium WebDriver

   ↓

Browser

For example:

Keyword: LOGIN

 

        ↓

 

LoginKeywords.login()

 

        ↓

 

LoginPage.login()

 

        ↓

 

Selenium WebDriver


46. POM With Hybrid Framework

POM is commonly used as one component of a Hybrid Framework.

             Hybrid Framework

                     |

       +-------------+-------------+

       |             |             |

      POM       Data-Driven   Keyword-Driven

       |             |             |

       +-------------+-------------+

                     |

                   TestNG

                     |

              Selenium WebDriver

                     |

                  Browser


47. POM and Separation of Concerns

One of the most important principles of POM is separation of responsibilities.

LayerResponsibility
Test LayerTest scenario and validation
Page LayerPage locators and page actions
Utility LayerReusable helper operations
Data LayerTest data
Configuration LayerEnvironment settings
Driver LayerWebDriver creation and management


48. Recommended POM Project Structure

SeleniumPOMFramework/

│

├── src/test/java/

│   ├── base/

│   │   └── BaseTest.java

│   │

│   ├── pages/

│   │   ├── LoginPage.java

│   │   ├── HomePage.java

│   │   ├── SearchPage.java

│   │   ├── ProductPage.java

│   │   ├── CartPage.java

│   │   └── CheckoutPage.java

│   │

│   ├── tests/

│   │   ├── LoginTest.java

│   │   ├── SearchTest.java

│   │   └── CheckoutTest.java

│   │

│   └── utilities/

│       ├── WaitUtil.java

│       ├── ExcelUtil.java

│       ├── ScreenshotUtil.java

│       └── ConfigReader.java

│

├── src/test/resources/

│   ├── config.properties

│   ├── testdata.xlsx

│   └── testng.xml

│

├── reports/

├── screenshots/

├── logs/

├── pom.xml

└── README.md


49. Role of BaseTest

BaseTest contains common setup and teardown operations.

  • Initialize WebDriver.
  • Open browser.
  • Configure browser.
  • Open application URL.
  • Close browser.
  • Provide common framework setup.


50. Role of Page Classes

Page classes contain:

  • Page-specific locators.
  • Page-specific actions.
  • Reusable business methods related to that page.
  • Page-level synchronization when appropriate.
  • Page-level state or validation methods when useful.


51. Role of Test Classes

Test classes should focus on test scenarios rather than low-level Selenium implementation.

@Test

public void validLoginTest() {

 

    LoginPage loginPage =

        new LoginPage(driver);

 

    loginPage.login(

        "testuser",

        "password"

    );

 

    Assert.assertTrue(

        homePage.isLogoutButtonDisplayed()

    );

}


52. POM With Configuration File

Application URLs and environment-specific settings can be kept outside the page classes.

browser=chrome

url=https://qa.example.com

timeout=10

This allows the framework to change environments without modifying individual page objects.


53. POM With Driver Factory

public class DriverFactory {

 

    public static WebDriver createDriver(

            String browser) {

 

        if (browser.equalsIgnoreCase("chrome")) {

            return new ChromeDriver();

        }

 

        if (browser.equalsIgnoreCase("firefox")) {

            return new FirefoxDriver();

        }

 

        if (browser.equalsIgnoreCase("edge")) {

            return new EdgeDriver();

        }

 

        throw new IllegalArgumentException(

            "Unsupported browser: " + browser

        );

    }

}

The page objects do not need to know how the browser was created. They simply receive a WebDriver instance.


54. POM With Page Navigation

A page method can return another page object when an action navigates to a different page.

public HomePage clickLogin() {

 

    driver.findElement(

        loginButton

    ).click();

 

    return new HomePage(driver);

}

The test can then write:

HomePage homePage =

    loginPage.clickLogin();

This style can make page transitions explicit.


55. Fluent Page Object Model

In a Fluent POM approach, page methods can return the same page object to allow method chaining.

public LoginPage enterUsername(

        String value) {

 

    username.sendKeys(value);

 

    return this;

}

 

public LoginPage enterPassword(

        String value) {

 

    password.sendKeys(value);

 

    return this;

}

 

public HomePage clickLogin() {

 

    loginButton.click();

 

    return new HomePage(driver);

}

Usage:

HomePage homePage =

    loginPage

        .enterUsername("user")

        .enterPassword("pass")

        .clickLogin();


56. POM With Component Objects

Modern applications may contain reusable components such as headers, menus, search bars, sidebars, cards, and navigation bars. These can also be represented as reusable objects.

HeaderComponent.java

NavigationComponent.java

SearchComponent.java

ProductCard.java

FooterComponent.java

This is useful when the same UI component appears on many pages.


57. Page Object vs Component Object

Page ObjectComponent Object
Represents a page or major screenRepresents a reusable UI component
Example: LoginPageExample: HeaderComponent
Usually page-specificCan be reused across pages


58. POM Locator Maintenance

Suppose the login button changes from:

By.id("login")

to:

By.id("loginButton")

With POM, the locator can be updated in the LoginPage class instead of searching through every test class for the old locator.


59. Without POM vs With POM

Without POMWith POM
Locators often repeatedLocators centralized
Test classes contain UI logicPage classes contain UI logic
Higher duplicationLower duplication
Harder maintenanceEasier maintenance
Less readable testsMore readable tests
Limited reusabilityHigher reusability


60. Advantages of POM

  • Maintainability: Locators are centralized in page classes.
  • Reusability: Page methods can be reused by multiple tests.
  • Readability: Tests describe business actions more clearly.
  • Reduced duplication: Common actions do not need to be rewritten.
  • Scalability: New pages can be added as separate classes.
  • Easy debugging: Page-specific issues can be isolated.
  • Better organization: Test and page logic are separated.
  • Team collaboration: Different team members can work on different page objects and tests.


61. Disadvantages of POM

  • Initial framework setup takes additional time.
  • Large applications may require many page classes.
  • Poorly designed page objects can become too large.
  • Frequent UI changes can still require page-object maintenance.
  • Excessive abstraction can make a framework difficult to understand.


62. Common POM Mistakes

  • Putting complete test scenarios inside page classes.
  • Putting assertions everywhere in page methods.
  • Creating one extremely large page class.
  • Duplicating locators.
  • Using unstable locators.
  • Hard-coding test data unnecessarily.
  • Using Thread.sleep() instead of appropriate waits.
  • Mixing browser setup with page-specific logic.
  • Creating methods that perform unrelated actions.
  • Returning incorrect page objects after navigation.


63. Best Practices for POM

  • Keep one logical page or component per class.
  • Use meaningful class names.
  • Keep locators private.
  • Use meaningful method names.
  • Keep page methods focused.
  • Use stable locators.
  • Use explicit waits where synchronization is required.
  • Keep test data outside page classes.
  • Keep browser initialization in a dedicated layer.
  • Keep assertions primarily in the test or validation layer.
  • Avoid unnecessarily large page classes.
  • Reuse common components.
  • Follow consistent coding standards.


64. POM Naming Conventions

TypeExample
Page ClassLoginPage
Test ClassLoginTest
UtilityExcelUtil
FactoryDriverFactory
MethodenterUsername()
Locator VariableloginButton


65. POM Package Structure

src/test/java

│

├── base

│   └── BaseTest.java

│

├── pages

│   ├── LoginPage.java

│   ├── HomePage.java

│   ├── ProductPage.java

│   └── CartPage.java

│

├── tests

│   ├── LoginTest.java

│   ├── ProductTest.java

│   └── CartTest.java

│

└── utilities

    ├── ExcelUtil.java

    ├── WaitUtil.java

    └── ScreenshotUtil.java


66. POM With Reporting

Reporting should generally be implemented outside individual page classes. The page objects perform actions, while listeners or reporting utilities capture test execution information.

Test

 ↓

Page Object

 ↓

WebDriver

 ↓

Application

 ↓

Test Result

 ↓

Listener

 ↓

Report


67. POM With Screenshots

A screenshot utility can be used independently of the page classes.

public class ScreenshotUtil {

 

    public static void capture(

            WebDriver driver,

            String fileName) {

 

        try {

 

            TakesScreenshot ts =

                (TakesScreenshot) driver;

 

            File source =

                ts.getScreenshotAs(

                    OutputType.FILE

                );

 

            File destination =

                new File(

                    "screenshots/"

                    + fileName

                    + ".png"

                );

 

            FileUtils.copyFile(

                source,

                destination

            );

 

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}


68. POM With Logging

Logging can be added around important framework actions.

logger.info("Entering username");

logger.info("Entering password");

logger.info("Clicking Login button");

logger.info("Login action completed");

The logging implementation should remain consistent with the framework's logging architecture.


69. POM With Selenium Grid

POM is independent of the physical browser location. The WebDriver can be local or remote, while page objects continue to use the WebDriver interface.

Test

 ↓

Page Object

 ↓

WebDriver

 ↓

Remote WebDriver

 ↓

Selenium Grid

 ↓

Browser Node

 ↓

Application


70. POM With Cross-Browser Testing

The same page objects can generally be reused across Chrome, Firefox, and Edge when the application behavior and locators are compatible.

             Page Objects

                  |

            WebDriver API

                  |

      +-----------+-----------+

      |           |           |

    Chrome     Firefox      Edge

      |           |           |

      +-----------+-----------+

                  |

            Web Application


71. POM With CI/CD

A POM-based framework can be executed through Maven in a CI/CD pipeline.

Git

 ↓

Jenkins

 ↓

Maven

 ↓

TestNG

 ↓

POM Tests

 ↓

Selenium WebDriver

 ↓

Browser

 ↓

Reports

 ↓

Build Result

JustAcademy's Selenium Training includes POM along with automation framework concepts such as Maven, Git, Jenkins, Selenium Grid, reporting, and CI/CD.


72. POM vs Normal Selenium Script

AspectNormal ScriptPOM
LocatorsOften inside testCentralized in page class
Page ActionsOften inside testPage methods
ReusabilityLimitedHigh
MaintenanceCan become difficultMore organized
ReadabilityLower for large testsHigher
ScalabilityLimitedBetter suited to larger suites


73. POM vs Data-Driven Framework

POMData-Driven Framework
Design patternTesting technique/framework approach
Focuses on page organizationFocuses on test-data separation
Manages page objectsManages multiple input datasets
Can be combined with Data-Driven TestingCan use POM for UI interaction


74. POM vs Keyword-Driven Framework

POMKeyword-Driven
Represents pages/componentsRepresents reusable actions as keywords
Manages locators and page actionsManages action execution
Can be used independentlyCan use POM underneath
Often part of larger frameworkCan be part of Hybrid Framework


75. POM and Hybrid Framework Relationship

POM is not itself a complete Hybrid Framework. It is a design pattern that can be used as a major layer inside a larger automation framework.

Hybrid Framework

      |

      +-- TestNG

      |

      +-- POM

      |

      +-- Data-Driven

      |

      +-- Keyword-Driven

      |

      +-- Utilities

      |

      +-- Reporting

      |

      +-- Logging

      |

      +-- CI/CD


76. Real-Time POM Architecture

                      TestNG

                         |

                    Test Classes

                         |

                    Page Objects

                         |

          +--------------+--------------+

          |              |              |

       Locators       Actions      Validations

          |              |              |

          +--------------+--------------+

                         |

                  Selenium WebDriver

                         |

                    Driver Factory

                         |

            +------------+------------+

            |            |            |

          Chrome      Firefox       Edge

                         |

                   Web Application

                         |

          +--------------+--------------+

          |              |              |

       Reports         Logs       Screenshots


77. Practical Project: Login Automation Using POM

Project Objective

Create a Selenium automation framework that validates different login scenarios using Page Object Model and TestNG.

Test Scenarios

  • Valid username and valid password.
  • Invalid username and valid password.
  • Valid username and invalid password.
  • Invalid username and invalid password.
  • Blank username.
  • Blank password.
  • Both fields blank.


78. Login Project Structure

LoginAutomation/

│

├── src/test/java/

│   ├── base/

│   │   └── BaseTest.java

│   ├── pages/

│   │   └── LoginPage.java

│   └── tests/

│       └── LoginTest.java

│

├── src/test/resources/

│   └── config.properties

│

├── pom.xml

└── testng.xml


79. Practical Assignment: E-Commerce POM

Create a POM-based automation project for an e-commerce application.

Pages to Create

  1. LoginPage
  2. HomePage
  3. SearchPage
  4. ProductPage
  5. CartPage
  6. CheckoutPage
  7. OrderConfirmationPage

Test Flow

Login

 ↓

Search Product

 ↓

Open Product

 ↓

Add Product

 ↓

Open Cart

 ↓

Checkout

 ↓

Place Order

 ↓

Verify Confirmation


80. POM Interview Questions

Q1. What is Page Object Model?

Page Object Model is a design pattern in Selenium where application pages or components are represented by classes containing their locators and interaction methods.

Q2. Why is POM used?

POM is used to improve maintainability, readability, reusability, and separation of test logic from page interaction logic.

Q3. What does a Page Object contain?

A Page Object commonly contains page-specific locators, WebDriver interactions, and reusable page/business methods.

Q4. Should test cases contain locators?

In a well-structured POM framework, page-specific locators are generally maintained in page classes rather than repeated throughout test classes.

Q5. What is the advantage of private locators?

Private locators provide encapsulation and encourage tests to interact with pages through meaningful page methods.


81. More POM Interview Questions

Q6. What is the role of the constructor in POM?

The constructor commonly receives the WebDriver instance and stores it so page methods can interact with the browser.

Q7. Can POM be combined with Data-Driven Testing?

Yes. Test data can be supplied through TestNG DataProvider, Excel, CSV, JSON, or other sources while page objects handle UI interaction.

Q8. Can POM be combined with Keyword-Driven Testing?

Yes. Keyword methods can call page-object methods to implement reusable business actions.

Q9. Can POM be used with TestNG?

Yes. TestNG can manage test execution while POM organizes page-level interactions.

Q10. Can POM be used in a Hybrid Framework?

Yes. POM is commonly used as one of the core layers of a Hybrid Selenium Framework.


82. Advanced POM Interview Questions

Q11. What happens if a locator changes?

Ideally, the locator is updated in the corresponding page object rather than in every test that uses the element.

Q12. Should assertions be written inside Page Objects?

Assertions are generally better kept in the test or dedicated validation layer, while page objects provide methods that expose useful application state.

Q13. What is Fluent POM?

Fluent POM allows page methods to return page objects or the current page object so that actions can be chained.

Q14. What is a component object?

A component object represents a reusable UI component such as a header, menu, search bar, or product card.

Q15. What is the difference between POM and PageFactory?

POM is a design pattern. PageFactory is an implementation approach historically used with Selenium's Page Object design to initialize WebElement fields annotated with @FindBy.


83. POM Best-Practice Checklist

  • Use separate page classes.
  • Keep locators private.
  • Use meaningful locator names.
  • Use meaningful action methods.
  • Keep page methods focused.
  • Keep test data outside page objects.
  • Keep browser management separate.
  • Use explicit waits where necessary.
  • Avoid duplicate locators.
  • Avoid unnecessarily large page classes.
  • Use component objects for reusable UI sections.
  • Use TestNG for organized execution.
  • Use reporting and logging at framework level.
  • Use version control.
  • Keep the framework consistent across the project.


84. Complete POM Execution Flow

Requirement

    ↓

Test Scenario

    ↓

Test Case

    ↓

TestNG Test

    ↓

BaseTest

    ↓

Driver Factory

    ↓

WebDriver

    ↓

Page Object

    ↓

Locator

    ↓

WebElement

    ↓

Browser Action

    ↓

Application

    ↓

Validation

    ↓

Report


85. POM Quick Revision Table

ConceptQuick Explanation
POMDesign pattern for organizing page interactions
Page ClassRepresents a page or application component
LocatorIdentifies a web element
Page MethodPerforms an action on the page
ConstructorReceives WebDriver
Test ClassContains test scenarios
BaseTestHandles common setup and teardown
Data-DrivenProvides multiple test-data sets
Keyword-DrivenProvides reusable action keywords
Hybrid FrameworkCombines multiple automation approaches


86. Course Resources

JustAcademy's Selenium Training includes Page Object Model as part of its Selenium automation framework curriculum, together with Data-Driven Testing, Keyword-Driven Testing, Hybrid Framework Design, reusable test architecture, reporting, logging, debugging, Selenium Grid, cross-browser testing, and CI/CD topics.

Selenium Training

Register for Course Demo


87. Final Summary

Page Object Model (POM) is a design pattern that organizes Selenium automation by representing application pages or reusable UI components as classes. These classes contain page-specific locators and methods, while test classes focus primarily on test scenarios and validations.

The major benefits of POM are maintainability, reusability, readability, reduced duplication, better organization, and scalability. POM can be combined with TestNG, Data-Driven Testing, Keyword-Driven Testing, Maven, reporting, logging, Selenium Grid, and CI/CD to create a complete Selenium automation framework.


88. One-Line Revision

POM = Separate Page Locators + Page Actions from Test Logic to create reusable, readable, maintainable, and scalable Selenium automation.


89. Important Learning Flow

Selenium WebDriver

        ↓

Locators

        ↓

WebElements

        ↓

TestNG

        ↓

Page Object Model

        ↓

Data-Driven Testing

        ↓

Keyword-Driven Testing

        ↓

Hybrid Framework

        ↓

Reporting & Logging

        ↓

Selenium Grid

        ↓

Git + Maven

        ↓

Jenkins + CI/CD

        ↓

Real-Time Automation Project

whatsapp